﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
using System.Runtime.Serialization;

namespace Chapter05_Lesson01
{
    class Program
    {
        static void Main(string[] args)
        {

            Serialize(new ShoppingCartItem(Convert.ToInt32(args[0]), Convert.ToDecimal(args[1]), Convert.ToInt32(args[2])));
        }

        private static void Serialize(ShoppingCartItem item)
        {
            SoapFormatter bf = new SoapFormatter();

            FileStream fs = new FileStream("teste.txt", FileMode.Create);
            bf.Serialize(fs, item);

            fs.Close();

            FileStream fs2 = new FileStream("teste.txt", FileMode.Open);
            ShoppingCartItem itemDeserialized = (ShoppingCartItem)bf.Deserialize(fs2);

            Console.WriteLine("quantity = " + itemDeserialized.quantity);
            Console.WriteLine("price = " + itemDeserialized.price);
            Console.WriteLine("product id = " + itemDeserialized.productID);
            Console.WriteLine("total = " + itemDeserialized.total);

            Console.ReadKey();

            fs2.Close();
        }
    }

    [Serializable]
    class ShoppingCartItem : IDeserializationCallback
    {
        public int productID;
        public decimal price;
        public int quantity;

        [NonSerialized]
        public decimal total;

        public ShoppingCartItem(int productID, decimal price, int quantity)
        {
            this.productID = productID;
            this.price = price;
            this.quantity = quantity;
            this.total = price * quantity;
        }

        #region IDeserializationCallback Members

        public void OnDeserialization(object sender)
        {
            this.total = this.price * this.quantity;
        }

        #endregion
    }
}
